<template>
    <div class="app-container">
      <projectHeader v-if="isShowTab" @tabClick="tabClick"></projectHeader>
        <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="auto" v-show="showSearch">
            <el-form-item label="手机号">
                <el-input
                    v-model="queryParams.phone"
                    placeholder="请输入手机号"
                    clearable
                    @keyup.enter="handleQuery"
                />
            </el-form-item>
            <el-form-item label="用户UID">
                <el-input
                    v-model="queryParams.userid"
                    placeholder="请输入用户UID"
                    clearable
                    @keyup.enter="handleQuery"
                />
            </el-form-item>
            <el-form-item label="设备编码">
                <el-input
                    v-model="queryParams.pileCode"
                    placeholder="请输入设备编码"
                    clearable
                    @keyup.enter="handleQuery"
                />
            </el-form-item>
            <el-form-item label="订单编号">
                <el-input
                    v-model="queryParams.orderCode"
                    placeholder="请输入订单编号"
                    clearable
                    @keyup.enter="handleQuery"
                />
            </el-form-item>
            <el-form-item label="订单状态">
                <el-select style="width: 200px;" v-model="queryParams.orderStatus"
                           clearable
                           placeholder="请选择">
                    <el-option
                        v-for="(item, index) in dict.type.chargin_order_status"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="创建时间">
              <el-date-picker
                v-model="dateRange"
                type="datetimerange"
                range-separator="-"
                start-placeholder="开始日期"
                value-format="yyyy-MM-dd HH:mm:ss"
                style="width:333px;"
                :default-time="['00:00:00','23:59:59']"
                end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <!-- 合计-->
        <el-row :style="{boxShadow: '0px 0px 6px rgba(0,0,0,0.12)', padding: '20px 0'}">

						<el-col :span="2">
						    <el-statistic title="订单数" :value="parseInt(summary.orderCount || 0)" />
						</el-col>
            <el-col :span="3">
                <el-statistic title="电费金额(元)" :value="parseFloat(summary.electricityAmount || 0)" :precision="2" />
            </el-col>
            <el-col :span="3">
                <el-statistic title="服务费金额(元)" :value="parseFloat(summary.serviceAmount || 0)" :precision="2" />
            </el-col>
            <el-col :span="2">
                <el-statistic title="充电电量(kwh)" :value="parseFloat(summary.electricQuantity || 0)" :precision="2" />
            </el-col>
            <el-col :span="2">
                <el-statistic title="充电时间(分钟)" :value="parseInt(summary.chargingMinute || 0)" />
            </el-col>
						<el-col :span="2">
						    <el-statistic title="	充电总费用(元)" :value="parseInt(summary.totalAmount || 0)" />
						</el-col>
            <el-col :span="3">
                <el-statistic title="实付金额(元)" :value="parseFloat(summary.actualAmount || 0)" :precision="2" />
            </el-col>
        </el-row>

        <el-row :gutter="10" class="mb8" style="margin-top: 20px;">
           <!-- <el-col :span="1.5">
                <el-button
                    type="warning"
                    plain
                    icon="Download"
                    @click="handleExport"
                    v-hasPermi="['system:consumer:export']"
                >导出
                </el-button>
            </el-col> -->
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-card>
            <div v-if="list.length > 0">
                <template v-for="row in list">
                    <div style="border-bottom: 1px dashed #CCC; margin-bottom: 10px;">
                        <el-row style="padding: 10px; background: #eff2f6;">
                            <el-col :span="3">
                                {{row.orderSn}}
                            </el-col>
                            <el-col :span="4">
															<span style="font-size: 12px;">{{ row.createTime }}</span>
                            </el-col>
                            <el-col :span="4">
															<span style="font-size: 12px;">ID:{{row.id}}</span>
                            </el-col>
                            <el-col :span="4" class="flex_hcneter">
															<span style="font-size: 12px;">支付类型:</span>
															<div style="font-size: 12px;">
                                <dict-tag :options="dict.type.chargin_order_paytype" :value="row.payType"/>
                              </div>
                            </el-col>
                        </el-row>
                        <el-row style="padding: 10px;" align="middle">
                            <el-col :span="8">
                                <el-row>
                                    <el-col>{{row.stationName}}</el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
																			<span class="mx-1" style="font-size: 12px;">充电口:{{row.port}}</span>
                                    </el-col>
                                    <el-col :span="12">
																			<span class="mx-1" style="font-size: 12px;">开始充电:{{ row.startTime }}</span>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
																			<span class="mx-1" style="font-size: 12px;">充电时长(分钟):{{row.chargingMinute}}</span>
                                    </el-col>
                                    <el-col :span="12">
																			<span class="mx-1" style="font-size: 12px;">结束充电:{{ row.endTime }}</span>
                                    </el-col>
                                </el-row>
                            </el-col>
                            <el-col :span="3" class="text-center">
                                <el-row>
                                    <el-col>
																			<span class="mx-1" style="font-size: 16px;">{{row.electricQuantity}}</span>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col>
																			<span class="mx-1" style="font-size: 12px;">已用电量(度)</span>
                                    </el-col>
                                </el-row>
                            </el-col>
                            <el-col :span="4" class="text-center">
                              <dict-tag :options="dict.type.chargin_order_status" :value="row.orderStatus"/>
                            </el-col>
                            <el-col :span="2" class="text-center">
                                <el-row>
                                    <el-col>
                                        <el-image :src="row.avatar" style="width: 60px; height: 60px;" />
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col>
																			<span>微信用户({{row.userid}})</span>
                                    </el-col>
                                </el-row>
                            </el-col>
                            <el-col :span="2" class="text-center">
                                <el-row>
                                    <el-col>
																			<span>{{row.nickName || ''}}</span>
                                    </el-col>
                                </el-row>
                            </el-col>
                            <el-col :span="2" class="text-center">
                                <el-row>
                                    <el-col>
																			<span style="font-size: 16px;">{{row.payableAmount}}</span>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col>
																			<span style="font-size: 12px;">当前订单金额(度)</span>
                                    </el-col>
                                </el-row>
                            </el-col>
                            <el-col :span="3" class="flex-center">
                                <el-button type="text" icon="el-icon-s-order" @click="handleShowOrderDialog(row)"
                                           v-hasPermi="['system:eaOrder:query']">查看订单
                                </el-button>
                                <el-button link type="text" icon="el-icon-edit-outline" @click="handleStop(row)"
                                           v-hasPermi="['system:eaOrder:endCharging']">停止充电
                                </el-button>
                                <el-button link type="text" v-if="row.money" icon="el-icon-s-release" @click="handleTuikuan(row)"
                                           v-hasPermi="['system:eaOrder:refund']">退款
                                </el-button>
                            </el-col>
                        </el-row>
                    </div>
                </template>
            </div>
            <div v-else>
                <el-empty description="没有数据" />
            </div>
        </el-card>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />

        <el-dialog :visible.sync="open" width="80%" append-to-body class="order-detail">
            <template #header="{ close, titleId, titleClass }">
                <div style="display: flex; justify-content: space-between; align-items: center; margin-top: 25px;">
                    <h4 :id="titleId" :class="titleClass" style="margin: 0;">充电订单详情</h4>
                    <span>全部充电订单 / 充电订单详情</span>
                </div>
            </template>
            <Order v-if="open" :key="active_order_id" :order_id="active_order_id" />
        </el-dialog>

        <!-- 添加或修改岗位对话框 -->
        <el-dialog :title="title" :visible.sync="open1" width="1000px" append-to-body>
          <el-form ref="form" :model="form" :rules="rules" label-width="120px">
            <el-row>
              <el-col :span="24">
                <el-form-item label="退款金额" prop="refundAmount">
                  <div class="flex_hcneter">
                    <el-input-number v-model="form.refundAmount" :precision="2" :min="0" :max="form.money"></el-input-number>
                    <span style="margin-left: 10px;color: red;">*注：最大退款金额：{{form.money || 0}}</span>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="open1 = false">取 消</el-button>
          </div>
        </el-dialog>
    </div>
</template>

<script>
  import moment from 'moment';
  import * as api from "@/api/user/consumer";
  import {getAllOperator} from "@/api/station/billing_rules";
  import {stopCharging} from "@/api/user/consumer";
  import Enums from "@/utils/enums";
  import {parseTime} from "@/utils/ruoyi";
  import Order from "@/components/Common/order/components/Order";
  export default {
    name: 'OrderList',
    components: { Order },
    dicts:['chargin_order_paytype','chargin_order_status'],
    props: {
      stationname: {
        type: String
      },
      gunId: {
        type: Number,
      },
      pileId: {
          type: Number
      },
      stationId: {
        type: Number
      },
      isShowTab: {
        type: Boolean,
        default:false,
      },
    },
    data() {
      return {
        Enums,
        list:[],
        // 总条数
        total: 0,
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        open1:false,
        loading:false,
        showSearch:true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        dateRange:[],
        active_order_id:0,
        operatorOptions:[],
        form: {},
        queryParams: {
          pageNum: 1,
          pageSize: 10,
        },
        rules: { },
        summary:[],
        plateform:{},//选择的平台项目
      };
    },
    mounted(){

      // this.initOperatorOptions()
      console.log('mounted')
    },
    methods: {
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if(this.form.refundAmount === 0) return this.$modal.msgWarning("退款金额不能为0");
            api.orderRefund(this.form).then(response => {
              this.$modal.msgSuccess("操作成功");
              this.open1 = false;
              this.getList();
            });
          }
        });
      },
      tabClick(e){//平台切换
        this.plateform = {...e}
        this.queryParams.pageNum = 1
        let queryParams = {...this.queryParams}
        if (this.stationname) {
            queryParams['stationname'] = this.stationname
        }
        if(this.gunId) {
          queryParams['gunId'] = this.gunId
        }
        if(this.pileId) {
          queryParams['pileId'] = this.pileId
        }
        if(this.stationId) {
            queryParams['stationId'] = this.stationId
        }
        this.queryParams = {...queryParams}
        this.getList();
        // this.getList()
        console.log('tabClick',e)
      },
      getSummary(){
        let queryParams = {...this.queryParams}
        if(!this.dateRange) this.dateRange = []
        if(this.dateRange.length) {
          queryParams.startTime = this.dateRange[0]
          queryParams.endTime = this.dateRange[1]
        }
        queryParams.platformType = this.plateform.value
      	queryParams['operat_id'] = this.$store.state.expires_in
      	api.summary(queryParams).then(response => {
      	    this.summary = response.data;
      	});
      },
      getList() {
        this.getSummary()
        this.loading = true;
        let queryParams = {...this.queryParams}
        if(!this.dateRange) this.dateRange = []
        if(this.dateRange.length) {
          queryParams.startTime = this.dateRange[0]
          queryParams.endTime = this.dateRange[1]
        }
        queryParams.platformType = this.plateform.value
        queryParams['operat_id'] = this.$store.state.expires_in
        api.listOrder(queryParams).then(response => {
          var d;
          var _list = response.rows || [];
          for (var i in _list) {
              d = moment.duration(_list[i].long_time, 'seconds');
              _list[i].format_long_time = Math.floor(d.asDays()) + '天' + d.hours() + '时' + d.minutes() + '分' + d.seconds() + '秒';
          }
          _list = _list.map(item=>{
            return {
              ...item,
              money: (item.payAmount || 0) - (item.refundAmount || 0)
            }
          })
          this.list = _list;
          this.total = response.total || 0;
          this.loading = false;
        });
      },
      formatterStatisticValue(value) {
        console.log('formatterStatisticValue', value)
        return value;
      },
      reset() {/** 表单重置 */
        this.form = {};
        this.resetForm("postRef");
      },
      handleQuery() {/** 搜索按钮操作 */
        this.queryParams.pageNum = 1;
        this.getList();
      },
      resetQuery() {/** 重置按钮操作 */
        this.dateRange = [];
        let obj = {...this.queryParams}
        this.queryParams = {
          pageNum: 1,
          pageSize: 10,
          platformType:this.plateform.value,
        };
        if(obj.pileId) this.queryParams.pileId = obj.pileId
        if(obj.gunId) this.queryParams.gunId = obj.gunId
        if(obj.stationId) this.queryParams.stationId = obj.stationId
        this.resetForm("queryRef");
        this.handleQuery();
      },
      handleSelectionChange(selection) {/** 多选框选中数据 */
        this.ids = selection.map(item => item.id);
        this.single = selection.length != 1;
        this.multiple = !selection.length;
      },
      handleShowOrderDialog(row) {
        this.open = true
        this.active_order_id = row.id

        console.log('handleShowOrderDialog', row, this.active_order_id)
      },
      handleStop(row) {
        this.$modal.confirm(`是否确认停止充电该数据项？`).then(function() {
          return api.stopCharging(row.id);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("操作成功");
        }).catch(() => {});
      },
      handleTuikuan(e){//退款
        this.title = '订单退款'
        this.open1 = true
        api.getOrderDetail(e.id).then(response => {
          let data = response.data || {};
          this.loading = false
          this.form = {
            orderId:e.id,
            money: (data.payAmount || 0) - (data.refundAmount || 0)
          }
        });

      },
    }
  }
</script>

<style lang="scss" scoped>
  .el-statistic {
      text-align: center;
  }
  .order-detail {
      .el-dialog__body {
          padding-top: 0 !important;
      }
  }
</style>
